package ua.amsoft.brelok.preference;

import ua.amsoft.brelok.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

/**
 * @author Tair Mustafaiev
 */
public class TimePreference extends DialogPreference {
    
    private int lastHour;
    private int lastMinute;
    private TimePicker picker;
    
    /**
     * Constructor
     * 
     * @param ctxt - {@link Context}
     * @param attrs - {@link AttributeSet}
     */
    public TimePreference(final Context ctxt, final AttributeSet attrs) {
        
        super(ctxt, attrs);
        setPositiveButtonText(R.string.pref_set);
        setNegativeButtonText(R.string.pref_cancel);
    }
    
    /**
     * Returns an hour
     * 
     * @param time - time
     * @return hour
     */
    public static int getHour(final String time) {
        final String[] timeParts = time.split(":");
        return Integer.parseInt(timeParts[0]);
    }
    
    /**
     * Returns minute
     * 
     * @param time - time
     * @return minutes
     */
    public static int getMinute(final String time) {
        final String[] timeParts = time.split(":");
        
        return Integer.parseInt(timeParts[1]);
    }
    
    @Override
    protected View onCreateDialogView() {
        this.picker = new TimePicker(getContext());
        this.picker.setIs24HourView(true);
        return this.picker;
    }
    
    @Override
    protected void onBindDialogView(final View v) {
        super.onBindDialogView(v);
        this.picker.setCurrentHour(this.lastHour);
        this.picker.setCurrentMinute(this.lastMinute);
    }
    
    @Override
    protected void onDialogClosed(final boolean positiveResult) {
        
        super.onDialogClosed(positiveResult);
        if (positiveResult) {
            this.lastHour = this.picker.getCurrentHour();
            this.lastMinute = this.picker.getCurrentMinute();
            
            final String time = String.valueOf(this.lastHour) + ":"
                    + String.valueOf(this.lastMinute);
            
            if (callChangeListener(time)) {
                persistString(time);
            }
        }
    }
    
    @Override
    protected Object onGetDefaultValue(final TypedArray a, final int index) {
        return a.getString(index);
    }
    
    @Override
    protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) {
        String time = "";
        if (restoreValue) {
            if (defaultValue == null) {
                time = getPersistedString("00:00");
            } else {
                time = getPersistedString(defaultValue.toString());
            }
        } else {
            time = defaultValue.toString();
        }
        
        this.lastHour = getHour(time);
        this.lastMinute = getMinute(time);
    }
}
